package com.greenline.search.test.httprequest.impl;

import com.greenline.search.test.httprequest.MyHttpRequest;
import com.greenline.search.test.httprequest.ResponseInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created with IntelliJ IDEA.
 * User: liulei
 * Date: 13-9-24
 * Time: 下午2:13
 * To change this template use File | Settings | File Templates.
 */
public class URLSolrHttpRequest implements MyHttpRequest {
    private Logger logger = LoggerFactory.getLogger(URLSolrHttpRequest.class);

    @Override
    public byte[] request(String url) {
        return new byte[0];  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public ResponseInfo requestAndGetResponseInfo(String url) {
        ResponseInfo responseInfo = new ResponseInfo();
        try {
            URL requestUrl = new URL(url);
            URLConnection connection = requestUrl.openConnection();
            connection.connect();
            InputStream inputStream = connection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String content = bufferedReader.readLine();
            logger.info("The request content is : {}",  content);
            if(content != null){
                int indexOfCount = content.indexOf("count");
                int indexOfFirstComma = content.indexOf(",");
                int indexOfQtime = content.indexOf("qtime");
                int indexOfSecondComma = content.indexOf(",",indexOfQtime);
                String strCount = content.substring(indexOfCount+7,indexOfFirstComma);
                String strQtime = content.substring(indexOfQtime+7,indexOfSecondComma);
                responseInfo.setQueryTimeMills(Integer.parseInt(strQtime));
                responseInfo.setReturnCount(Integer.parseInt(strCount));
                if(strCount.equals("0")){
                    logger.info("The request url is: " + url);
                }
            }
            bufferedReader.close();
            inputStream.close();
        } catch (MalformedURLException e) {
            System.out.println("URl is invalid!");
        } catch (IOException e) {
            System.out.println("Open connection failed!");
        }
        return responseInfo;
    }

    public static void main(String[] args) {
        String url = "http://192.168.1.37:9082/doctor_search?q=%E7%B3%96%E5%B0%BF%E7%97%85";
        MyHttpRequest myHttpRequest = new URLSolrHttpRequest();
        ResponseInfo info = myHttpRequest.requestAndGetResponseInfo(url);
        System.out.println(info.getQueryTimeMills());
        System.out.println(info.getReturnCount());
    }
}
